<template>
 <a-card 
  :bordered="false">
  <CrudTable
    ref="tableRef"
    :columns="columns"
    :fetchData="fetchData"
    @rowClick="tableRowClick">
    <template #toolBtn>
      <a-space :size="100">
        <a-button type="primary" @click="onAddPerson">
          <template #icon>
            <icon-user-add />
          </template>
          <span>新增员工</span>
        </a-button>
        <div class="formSearch">
           <a-form layout="inline" :model="searchModal"
           @submit="handleSubmitSearch" class="searchForm" auto-label-width>
           <a-form-item field="status" label="员工回收站:">
            <a-select v-model="searchModal.status"  
              :style="{ width:'200px'}" 
              placeholder="请选择" allow-clear>
              <a-option value="normal">正常</a-option>
              <a-option value="delete">废弃</a-option>
            </a-select>
           </a-form-item>
           <a-form-item hide-label>
            <a-button type="primary" html-type="submit">搜索</a-button>
           </a-form-item>
           </a-form>
        </div>
      </a-space>
    </template>
    <template #entryStatusSlot="{ record }">
      <a-switch v-model="record.entry_status" 
       :checked-value="1" :unchecked-value="0"
      :beforeChange="entryStatusChange"/>
    </template>
    <template #statusSlot="{ record }">
      <a-switch v-model="record.status" 
      checked-value="normal" unchecked-value="stop"
      :beforeChange="statusChange"/>
    </template>

    <template #editSlot="{ record }">
      <a-button type="primary" @click="onEdit(record)">
        <template #icon><icon-edit /></template>
        <span>编辑</span>
      </a-button>
    </template>

    <template #deleteSlot="{ record }">

      <a-button v-if="record.status == 'delete'"
       type="primary" @click="onRecovery(record?.id)">
        <span>恢复</span>
      </a-button>

      <a-button v-if="['normal','stop'].includes(record.status)" 
        type="primary" status="danger" @click="onDelete(record)">
        <template #icon><icon-delete /></template>
        <span>删除</span>
      </a-button>
    </template>
  </CrudTable> 

  <a-modal width="200px" simple
    v-model:visible="visibleConfirt"
    :footer="false" title-align="start">
      <a-button type="primary"
      size="large" status="danger" long
      :loading="detLoading" @click="onConfirmDelete">确定删除</a-button>
      <a-button type="primary" size="large" 
      long style="margin-top: 20px;"
      @click="onDeleteClose">返回</a-button>
  </a-modal>  
  
  <a-modal width="400px"
    v-model:visible="visibleSelect"
    :footer="false" title-align="start" 
    class="comomModal" :maskClosable="false">
    <template #title>
      <div class="model-title-text">请谨慎删除</div>
    </template>
    <a-radio-group v-model="selectType">
      <template v-for="(item, index) in radioGroup" :key="index">
        <a-radio :value="item.value">
          <template #radio="{ checked }">
            <a-space align="center"
              class="custom-radio-card"
              :class="{ 'custom-radio-card-checked': checked }">
              <div className="custom-radio-card-mask">
                <div className="custom-radio-card-mask-dot">
                </div>  
              </div>
              <div>
                <div className="custom-radio-card-title">
                      {{ item.label }}
                </div>
              </div>
            </a-space>
          </template>
        </a-radio>
      </template>
    </a-radio-group>

    <div style="text-align: right;width: 100%; margin-top: 20px;">
      <a-space style="justify-content: flex-end;">
        <a-button size="medium"  class="deleteBtn" @click="confirmedTip">确认删除</a-button>
        <a-button size="medium" type="primary" @click="onDeleteClose">返回</a-button>
      </a-space>
    </div>
  </a-modal>
  
</a-card>
</template>

<script setup lang="ts">
import { ref , reactive } from 'vue'
import lodash from 'lodash';
import { 
  updatePersonStatus,
  deletePersonnel,
  getPersonnelList
} from "@/api/personnel";

import type { PersonelItem } from "@/api/personnel";
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
const router = useRouter();

let tableRef = ref()
let visibleSelect = ref(false);
let visibleConfirt = ref(false);
let detLoading = ref(false);
let selectType = ref('1')
let searchModal = reactive<any>({
    status: '',
})


let radioGroup = ref([
   {
     label: '仅删除账号，数据保留',
     value: '1',
   }
])

const columns = [
  {
    title: 'ID',
    dataIndex: 'uid',
    align: 'center'
  },
  {
    title: '客户经理',
    dataIndex: 'nickname',
    align: 'center'
  },
  // {
  //   title: '登陆账号',
  //   align: 'center',
  //   dataIndex: 'username',
  // },
  {
    title: '登录手机号码',
    dataIndex: 'mobile',
    align: 'center',
  },
  {
    title: '进件状态',
    dataIndex: 'entry_status',
    align: 'center',
    slotName: 'entryStatusSlot'
  },
  {
    title: '账号状态',
    dataIndex: 'status',
    align: 'center',
    slotName: 'statusSlot'
  },
  {
    title: '编辑账号',
    align: 'center',
    slotName: 'editSlot'
  },
  {
    title: '删除账号',
    align: 'center',
    slotName: 'deleteSlot'
  },
];

const handleSubmitSearch = ({errors ,values }: any)=>{
    tableRef.value.reloadEvent();
}

let selectItem = ref<PersonelItem>()
const tableRowClick = (result)=>{
  selectItem.value = result
}


const fetchData = ({ page, size }) : any=>{
   let status = searchModal.status;
   return getPersonnelList({ page, size, status })
   .then(({ data })=>{
      let newData: any[] = [];
      let personData = data?.datalist?.data;
      personData.forEach((item: any, index: number) => { 
        newData.push({ ...item, index: index + 1 })
      });

      return { 
        data: newData || [],
        total: data?.datalist?.total || 0
      }
    })
}

const entryStatusChange = async (newValue): Promise<boolean | void>=> {
  return new Promise((resolve, reject) => {
    setTimeout(()=> {
      updatePersonStatus({
          id: selectItem.value?.id,
          entry_status: newValue
       }).then((res: any)=>{
        if(res.code == 1){
          Message.success("修改成功")
          resolve(true);
          tableRef.value.reloadEvent();
        } else {
          reject()
          Message.error("修改失败")
        }
       }).catch(()=>{
          reject()
       })
    }, 300)
  })
}

const statusChange = async (newValue: any) : Promise<boolean | void> => {
  return new Promise((resolve, reject) => {
    setTimeout(()=> {
      updatePersonStatus({
        status: newValue,
        id: selectItem.value?.id,
       }).then((res: any)=>{
        if(res.code == 1){
          Message.success("修改成功")
          resolve(true);
          tableRef.value.reloadEvent();
        } else {
          reject()
          Message.error("修改失败")
        }
       })
    }, 300)
  })
}

const onEdit = (data: any)=>{
  router.push({
    query: { uid: data.id },
    path: '/personnel/editPersonnel'
  })
}

let deleteItem = ref()
const onDelete = (data: any)=>{
  deleteItem.value = data;
  visibleSelect.value = true;
}

const confirmedTip = (data)=>{
  visibleConfirt.value = true;
}


const onDeleteClose = ()=>{
  selectType.value = '1';
  visibleSelect.value = false;
  visibleConfirt.value = false;
}

const onRecovery = (uid: number)=>{
  deletePersonnel({
    id: uid,
    status: 'normal'
  }).then(({ code }: any)=>{
    if(code == 1){
      Message.success('恢复成功')
      tableRef.value.reloadEvent();
    }
  })
}

const onConfirmDelete = ()=>{
  deletePersonnel({
    id: deleteItem.value.id,
    status: 'delete'
  }).then(({ code }: any)=>{
    if(code == 1){
      Message.success('删除成功')
      onDeleteClose();
      tableRef.value.reloadEvent();
    }
  })
}

const onAddPerson = ()=>{
  router.push({ path: '/personnel/addPersonnel' })
}

</script>

<style scoped lang='less'>
  .custom-radio-card {
    padding: 21px 146px 21px 22px;
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    width: 100%;
    margin-bottom: 12px;
    align-content: center;
    box-sizing: border-box;
  }

  .custom-radio-card-mask {
    height: 14px;
    width: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
  }

  .custom-radio-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 100%;
  }

  .custom-radio-card-title {
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }

  .custom-radio-card:hover,
  .custom-radio-card-checked,
  .custom-radio-card:hover .custom-radio-card-mask,
  .custom-radio-card-checked  .custom-radio-card-mask{
    border-color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked {
    background-color: var(--color-primary-light-1);
  }

  .custom-radio-card:hover .custom-radio-card-title,
  .custom-radio-card-checked .custom-radio-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked .custom-radio-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }

  .searchForm{
    width: auto;
    margin-bottom: 0px !important;
  }


  .deleteBtn{
    font-weight: bold;
    font-size: 14px;
    color: #F42626;
    background: #FFFFFF;
    border-radius: 4px 4px 4px 4px;
    border: 1px solid #A7AFBF;
  }

</style>